import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home/Index.vue";
// import Layout from "@/components/layout/Index.vue";
import Layout from "../components/layout/Index.vue";
import store from "@/store";
import authRoutes from "@/mock/route";
import localRoutes from "@/router/localRoutes";

Vue.use(VueRouter);

let generateRoutes = transformRouter(authRoutes.concat(localRoutes));
// console.log(generateRoutes);

const routes = [
  {
    path: "/test",
    name: "Test",
    component: () => import("@/views/Test.vue"),
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/Auth/BaseLogin.vue"),
  },
  // {
  //   path: "home",
  //   name: "home",
  //   component: Home,
  // },

  // {
  //   name: "Index",
  //   path: "/",
  //   component: () => import("@/components/layout/Index.vue"),
  //   children: generateRoutes,
  // },

  // {
  //   path: "/about",
  //   name: "about",
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () =>
  //     import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  // },
];

const router = new VueRouter({
  mode: "history",
  routes,
});

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

// console.log(router);

router.beforeEach((to, from, next) => {
  //添加路由数据

  // 放开登录页路由
  if (to.path == "/login") return next();

  // 不存在 token 跳转登录页
  if (!localStorage.getItem("token")) {
    return next("/login");
  }

  // 路由表匹配成功 直接跳转
  if (to.matched.length > 0) {
    return next();
  }

  if (store.state == null || sessionStorage.getItem("store") == null) {
    return next("/login");
  }

  let asyncRouters = [];

  // 检查 vuex 或 sessionStorage 中是否有缓存路由
  if (store.state.system.routes.length > 0) {
    asyncRouters = store.state.system.routes;
  } else {
    let sessionStore = JSON.parse(sessionStorage.getItem("store"));
    asyncRouters = sessionStore.system.routes;
  }

  // 如果存在服务端路由 重新加载路由表
  if (asyncRouters.length > 0) {
    router.addRoute({
      name: "Index",
      path: "/",
      component: () => import("@/components/layout/Index.vue"),
      children: transformRouter(asyncRouters),
    });

    return next(to);
  } else {
    return next("/login");
  }
});

function transformRouter(list) {
  return list.map((item) => {
    if (item.children) transformRouter(item.children);

    if (item.link_url != undefined) {
      item.name = item.link_url;
      item.path = item.link_url;
    }
    if (item.Component && item.menu_type == 2) {
      item.component = () => import(`@/${item.Component}.vue`);
    } else {
      item.component = { render: (e) => e("router-view") };
    }
    return item;
  });
}

export default router;
